package edu.fight.shiro.realm;

import com.alibaba.fastjson.JSONObject;
import edu.fight.entity.User;
import edu.fight.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.Arrays;

//@Component
@Slf4j
public class MyRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    public void setName(String name) {
        super.setName(this.getClass().getName());
    }

    /**
     * 认证方法
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        try {
            // 1. 获取login的登录用户、密码
            UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
//            Object principal = token.getPrincipal();
//            Object credentials = token.getCredentials();
            String username = token.getUsername();
            String password = new String(token.getPassword());

            // 2. 根据用户名查库
            User user = userService.findByUsername(username);
            // 3. 判断登录用户与库用户是否一致
            if (!ObjectUtils.isEmpty(user) && user.getPasswd().equals(password)) {
                SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,user.getPasswd(),getName());
                return info;
            }else {
                throw new RuntimeException("异常：库中取数为空或密码不一致");
            }
            // 4. 若一致，返回用户信息；否则，抛出异常
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            throw new RuntimeException("登录用户异常: "+e.getMessage());
        }
    }

    /**
     * 授权方法
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        User primaryPrincipal = (User) principals.getPrimaryPrincipal();
//        System.out.println(primaryPrincipal);

        // 添加角色
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
//        simpleAuthorizationInfo.add
//        simpleAuthorizationInfo.addRoles(Arrays.asList("admin","user","guest"));
//        simpleAuthorizationInfo.addStringPermissions(Arrays.asList("user:*:*","order:*:*","product:*:*","schedule:*:*","customer:*:*"));


//        System.out.println("=== MyRealm extends AuthorizingRealm doGetAuthorizationInfo===:"+JSONObject.toJSONString(principals));
        return null;
    }

}
